package com.android.mios;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.android.mios.adapter.SceneGridViewAdapter;
import com.android.mios.intenet.PollLoop;
import com.android.mios.listener.SceneChangedListener;
import com.android.mios.model.Scene;
import com.android.mios.util.Global;

import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;

public class SceneControlActivity extends Activity {

	private List<Scene> sceneOfArray;
	private GridView mGridView;
	private SceneGridViewAdapter mScenceGridViewAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scene_contrl_layout);
		initData();
		initView();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		updateDevice();
		PollLoop.getInstance().addSceneChangedListener(sceneListener);

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		PollLoop.getInstance().removeSceneChangedListener(sceneListener);
	}

	private void initData() {

		sceneOfArray = new ArrayList<Scene>();
		mScenceGridViewAdapter = new SceneGridViewAdapter(this, sceneOfArray,
				R.layout.scene_contrl_item);

	}

	private void initView() {

		initGridView();
	}

	private void initGridView() {

		mGridView = (GridView) findViewById(R.id.GV_SceneControl);

		mGridView.setAdapter(mScenceGridViewAdapter);

	}

	protected List<Scene> getSceneList(int serialNumber,int roomId) {
		// TODO Auto-generated method stub
		Map<String, Scene> allScenes = PollLoop.getInstance().getScenes();

		List<Scene> scenes = Scene.findScenesByRoom(allScenes,serialNumber, roomId);

		return scenes;
	}

	private SceneChangedListener sceneListener = new SceneChangedListener() {
		Runnable updateListTask = new Runnable() {
			public void run() {
				updateDevice();
			}
		};

		public void scenesChanged() {
			runOnUiThread(updateListTask);
		}
	};

	protected void updateDevice() {
		// TODO Auto-generated method stub
		sceneOfArray.clear();
		sceneOfArray.addAll(getSceneList(Global.getInstance().getSerialNumber(),Global.getInstance().getRoomID()));
		mScenceGridViewAdapter.notifyDataSetChanged();
	}
}
